package com.qk.management.controller;

import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.entity.Dept;
import com.qk.management.aop.anno.LogAnno;
import com.qk.management.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/depts")
@Slf4j
public class DeptController {

    @Autowired
    private DeptService deptService;


    @GetMapping
    public Result page(@Param("name") String name, @Param("status") Integer status,
                       @Param("page") Integer page, @Param("pageSize") Integer pageSize) {
        log.info("分页查询部门,参数:部门名称={},部门状态={},当前页码={},每页大小={}", name, status, page, pageSize);
        PageResult<Dept> pageResult = deptService.page(name, status, page, pageSize);
        log.info("pageResult={}", pageResult);
        return Result.success(pageResult);
    }

    @PostMapping
    @LogAnno
    public Result addDept(@RequestBody Dept dept) {
//        try {
            log.info("新增部门:{}",dept);
            deptService.addDept(dept);

            return Result.success();
//        } catch (Exception e) {
//            log.error("新增部门失败:{}",e.getMessage());
//            return Result.error("新增部门失败");
//        }
    }

    @LogAnno
    @DeleteMapping("/{id}")
    public Result deleteDept(@PathVariable Integer id) {
        //异常模拟
       // int i = 1 / 0;
        log.info("删除部门id:{}",id);
        deptService.deleteDept(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getDept(@PathVariable Integer id) {
        log.info("查询部门id:{}",id);
        Dept dept = deptService.getDept(id);
        return Result.success(dept);
    }

    @LogAnno
    @PutMapping
    public Result updateDept(@RequestBody Dept dept) {
        log.info("修改部门:{}",dept);
        deptService.updateDept(dept);
        return Result.success();
    }

    @GetMapping("list")
    public Result listDept() {
        List<Dept> depts = deptService.listDept();
        return Result.success(depts);
    }
}